package com.sinping.qh.service.auth.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sinping.qh.api.exception.HandlerException;
import com.sinping.qh.api.support.ConstEum;
import com.sinping.qh.domain.auth.Resource;
import com.sinping.qh.domain.auth.User;
import com.sinping.qh.domain.auth.UserRole;
import com.sinping.qh.domain.user.ContentInfo;
import com.sinping.qh.domain.user.TokenInfo;
import com.sinping.qh.domain.user.UserInfo;
import com.sinping.qh.dto.auth.ResourceDTO;
import com.sinping.qh.dto.auth.UserAndResDTO;
import com.sinping.qh.dto.auth.UserDTO;
import com.sinping.qh.repository.mongo.user.ContentInfoRepository;
import com.sinping.qh.repository.mongo.user.TokenRepository;
import com.sinping.qh.repository.mongo.user.UserInfoRepository;
import com.sinping.qh.repository.mysql.dao.UserMapper;
import com.sinping.qh.service.auth.IResourceService;
import com.sinping.qh.service.auth.ISessionService;
import com.sinping.qh.service.auth.IUserRoleService;
import com.sinping.qh.service.auth.IUserService;
import com.sinping.qh.service.redis.RedisCommon;
import com.sinping.qh.service.redis.RedisService;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.security.CryptoUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author houjiawei
 * @copyright 2017 sinping.com 北京芯平科技股份有限公司. All rights reserved.
 * 本内容仅限于北京芯平科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 * <p>
 * package com.sinping.woniu.service.auth.impl;
 * /**
 * 用户服务类实现
 * @create 2017/12/18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IResourceService resourceService;

    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    TokenRepository tokenRepository;
    @Qualifier("sessionServiceRedisImpl")
    @Autowired
    private ISessionService iSessionService;
   @Autowired
   private RedisService redisService;

    @Autowired
    ContentInfoRepository contentInfoRepository;

    @Override
    public User validateUserLogin(User user) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        User user1 = new User();
        user1.setUsername(user.getUsername().trim());

//        String PasswordCry = CryptoUtil.createSha256(salt,user.getUserContent().trim());
//        user1.setUserContent(PasswordCry);
        user1.setDeleted(0);//  0 没有删除 　　1已经删除
        userEntityWrapper.setEntity(user1);
        User user2 = this.selectOne(userEntityWrapper);
        if(user2==null){
            return null;
        }

        ContentInfo contentInfo=contentInfoRepository.findContentInfoByUserId(user2.getId());
        String saleStr="";
        if(contentInfo!=null){
            saleStr=contentInfo.getSalt();
        }
        else{
            throw new HandlerException(ConstEum.FAIL,"账号异常,请联系管理员");
        }

        byte[] salt= Base64Utils.decodeFromString(saleStr);

        if(user2.getContent().equals(CryptoUtil.sha256(salt,user.getContent()))) {
            return user2;
        }
        return null;
    }

    @Override
    public UserDTO loadUserDtoByUserId(String id) {
        User userFromDB = this.selectById(id);
        UserDTO userDTO = BeanMapper.map(userFromDB, UserDTO.class);
        return userDTO;
    }


    @Override
    public UserAndResDTO loadUserAndResourceDTO(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        User userFromDB = this.selectById(id);
        if (userFromDB != null) {

            //用户表没有角色ID，单独查询  update by chenchangshi
            List<UserRole> roles = userRoleService.getRolseByUserId(id);
            if(roles!=null && roles.size()==1){
                userFromDB.setRoleid(roles.get(0).getRoleId());
            }
            //end

            List<Resource> resourceByUserId = resourceService.getResourceByUserId(id);
            UserAndResDTO userAndResDTO = new UserAndResDTO();
            List<ResourceDTO> treeByResource=new ArrayList<>();
            if(resourceByUserId!=null){
                 treeByResource = resourceService.createTreeByResource(resourceByUserId);

            }
            userAndResDTO.setResourceDTOList(treeByResource);
            UserDTO userDTO = BeanMapper.map(userFromDB, UserDTO.class);
            userAndResDTO.setUserInfo(userDTO);
            return userAndResDTO;
        } else {
            return null;
        }
    }

    @Override
    public UserInfo findMongoUserExist(User user) {

        UserInfo one = userInfoRepository.findOne(user.getId());

        return one;
    }

    @Override
    public UserInfo updateMongoUserInfo(UserInfo one) {

        UserInfo save = userInfoRepository.save(one);
        /** 清除后台 token*/
        iSessionService.deleteSessionAndTokenByUserid(save.getId());

        /** 清除app token*/
        TokenInfo tokenInfoByUserId = tokenRepository.findTokenInfoByUserId(save.getId());
        if (tokenInfoByUserId != null) {
//            iSessionMongoService.deleteSessionByToken(tokenInfoByUserId.getToken());
            redisService.expireKey(RedisCommon.RedisPrimaryKey.UserSessionByApp.getFirstKey()+tokenInfoByUserId.getToken());
        }

        return save;
    }
}
